package io.github.wanggit.antrpc.console.zookeeper;

import io.github.wanggit.antrpc.commons.utils.JsonUtils;
import io.github.wanggit.antrpc.commons.zookeeper.NodeUnregDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
@Component
public class DefaultUnregNodeContainer implements IUnregNodeContainer {

    private final ConcurrentHashMap<String, CopyOnWriteArrayList<NodeUnregDTO>> container =
            new ConcurrentHashMap<>();

    @Override
    public void add(NodeUnregDTO nodeUnregDTO) {
        String unregDTOClazz = nodeUnregDTO.getClazz();
        if (!container.containsKey(unregDTOClazz)) {
            synchronized (unregDTOClazz.intern()) {
                if (!container.containsKey(unregDTOClazz)) {
                    container.put(unregDTOClazz, new CopyOnWriteArrayList<>());
                }
            }
        }
        if (log.isInfoEnabled()) {
            log.info("Add " + JsonUtils.toJsonString(nodeUnregDTO));
        }
        container.get(unregDTOClazz).add(nodeUnregDTO);
    }

    @Override
    public void delete(NodeUnregDTO nodeUnregDTO) {
        String unregDTOClazz = nodeUnregDTO.getClazz();
        if (container.containsKey(unregDTOClazz)) {
            if (log.isInfoEnabled()) {
                log.info("Delete " + JsonUtils.toJsonString(nodeUnregDTO));
            }
            container.get(unregDTOClazz).remove(nodeUnregDTO);
        }
    }

    @Override
    public List<NodeUnregDTO> findNodeUnregDTOs(String className) {
        List<NodeUnregDTO> nodeUnregDTOS = container.get(className);
        if (null == nodeUnregDTOS) {
            return new ArrayList<>();
        }
        nodeUnregDTOS.sort(Comparator.comparing(NodeUnregDTO::getHost));
        return nodeUnregDTOS;
    }

    @Override
    public Set<String> findAll() {
        return new HashSet<>(container.keySet());
    }
}
